﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Web;
using System.Text.RegularExpressions;

namespace Hands.LoginControl
{
    internal static class ConfigFileReader
    {
        private const string CONFIG_FILE_NAME = "Valkyrja.xml";

        private const string KEEP_USER_STATE_NODE_NAME = "keep-the-user-state";
        private const string FOCRED_URI = "focred-uri";

        private const int WAY = 0;
        private const int FLAG_BIT = 1;
        private const int REDIRECT_TO = 2;

        private const int ROOT = 0;

        static ConfigFileReader()
        {
            readConfig();
        }

        internal static void readConfigToStorage() { }

        private static void readConfig()
        {
            //设置配置文件的读取路径为网站项目的根目录
            StringBuilder configFilePath = new StringBuilder();
            configFilePath.Append(HttpRuntime.AppDomainAppPath.ToString());
            configFilePath.Append(CONFIG_FILE_NAME);

            XmlDocument xml = new XmlDocument();
            xml.Load(configFilePath.ToString());

            //读取keep-the-user-state节点配置信息
            XmlNodeList keepUserStateNode = xml.GetElementsByTagName(KEEP_USER_STATE_NODE_NAME);
            UserState.init(keepUserStateNode[0].Attributes[WAY].Value, keepUserStateNode[0].Attributes[FLAG_BIT].Value, keepUserStateNode[0].Attributes[REDIRECT_TO].Value);

            //读取所有的focred-uri和其子节点branch的配置信息
            XmlNodeList forcedUriNodes = xml.GetElementsByTagName(FOCRED_URI);
            StringBuilder roots = new StringBuilder();
            foreach (XmlNode node in forcedUriNodes)
            {
                createRegex(node.Attributes[ROOT].Value, ref roots);

                StringBuilder branchs = new StringBuilder();
                foreach (XmlNode branchNode in node.ChildNodes)
                {
                    createRegex(branchNode.InnerText, ref branchs);
                }
                UriBranch uriBranch = new UriBranch(new Regex(branchs.ToString(), RegexOptions.Compiled));

                ConfigStorage.addRoot(node.Attributes[ROOT].Value, uriBranch);
            }
            UriBranchQuery.addRootRegex(new Regex(roots.ToString(), RegexOptions.Compiled));
        }

        private static void createRegex(string value, ref StringBuilder set)
        {
            if (set.Length == 0)
            {
                set.Append(value);
            }
            else
            {
                set.Append("|");
                set.Append(value.Contains(".") ? value.Replace(".", "\\.") : value);
            }
        }

    }
}
